package com.syf.boot;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.syf.disruptor.DisruptorTemplate;
import com.syf.domain.EntrustOrder;
import com.syf.mapper.EntrustOrderMapper;
import com.syf.util.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import java.util.List;

/**
 * 初始数据的加载：
 *      用于测试：从数据库查询处理，丢进RingBuffer
 *      真正实现： 将委托单数据 丢进RocketMq ,再监听RocketMq 存储进RingBuffer
 *
 */
@Component
public class DataLoaderCmdRunner implements CommandLineRunner {


    @Autowired
    private EntrustOrderMapper entrustOrderMapper ; //委托订单

    @Autowired
    private DisruptorTemplate disruptorTemplate ; //高速无锁队列


    /**
     * 项目启动完毕后会--自动执行该方法【用于测试】
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //查询出所有未交易的委托单
        List<EntrustOrder> entrustOrders = entrustOrderMapper.selectList(
                new LambdaQueryWrapper<EntrustOrder>()
                        .eq(EntrustOrder::getStatus, 0)
                        .orderByAsc(EntrustOrder::getCreated)
        );
        if(CollectionUtils.isEmpty(entrustOrders)){
            return;
        }

        //测试程序执行 用时
        StopWatch stopWatch = new StopWatch() ;
        stopWatch.start();  //开始计时

        //将所有的委托单--放进 RingBuffer高速无锁队列
        for (EntrustOrder entrustOrder : entrustOrders) {
            disruptorTemplate.onData(BeanUtils.entrustOrder2Order(entrustOrder));  //将EntrustOrder 转化为我们的Order
        }

        stopWatch.stop();   //计时结束
        long lastTaskTimeMillis = stopWatch.getLastTaskTimeMillis();  //总共耗时(ms)
        System.out.println("总条数:+"+entrustOrders.size()+" ,总共耗时:"+lastTaskTimeMillis+"ms");

    }


}
